
import { _decorator, Component, Node, RigidBody, Vec3, input, Input, EventTouch, RigidBodyComponent, ColliderComponent, ITriggerEvent, director, PhysicsSystem, math, v3, Canvas } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PlayerJoystick')
export class PlayerJoystick extends Component {
    @property(Node)
    stick: Node = null; // 摇杆手柄
    
    @property
    maxRadius: number = 80; // 摇杆最大半径
    
    private _centerPos: Vec3 = new Vec3(); // 摇杆中心位置
    private _direction: Vec3 = new Vec3(0, 0, 0); // 移动方向
    private _isActive: boolean = false; // 摇杆是否激活

    onLoad() {
        // 记录初始位置
        this._centerPos = this.node.position.clone();
        
        // 注册触摸事件
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        input.on(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    onDestroy() {
        // 移除事件监听
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        input.off(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    onTouchStart(event: EventTouch) {
        // const touchPos = event.getLocation();
        // const localPos = this.node.parent.getComponent(Canvas).camera.screenToWorld(touchPos);
        
        // // 激活摇杆
        // this._isActive = true;
        // this.node.setPosition(localPos);
    }

    onTouchMove(event: EventTouch) {
        // if (!this._isActive) return;
        
        // const touchPos = event.getLocation();
        // const localPos = this.node.parent.getComponent(Canvas).camera.screenToWorld(touchPos);
        
        // // 计算摇杆方向
        // const offset = new Vec3(localPos.x - this.node.position.x, localPos.y - this.node.position.y, 0);
        // const length = offset.length();
        
        // // 限制摇杆移动范围
        // if (length > this.maxRadius) {
        //     offset.multiplyScalar(this.maxRadius / length);
        // }
        
        // // 更新摇杆手柄位置
        // this.stick.setPosition(offset);
        
        // // 计算归一化方向
        // this._direction.set(offset);
        // this._direction.normalize();
    }

    onTouchEnd() {
        // 重置摇杆
        this._isActive = false;
        this.stick.setPosition(Vec3.ZERO);
        this._direction.set(Vec3.ZERO);
        this.node.setPosition(this._centerPos);
    }

    // 获取当前摇杆方向
    get direction(): Vec3 {
        return this._direction;
    }
    
    // 获取摇杆激活状态
    get isActive(): boolean {
        return this._isActive;
    }
}